package rpc;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2025-03-26
 * Time: 20:09
 */
public class Server {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1. 建立连接(Connection)
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置连接参数:ip,端口号,用户名,密码,虚拟机
        connectionFactory.setHost("116.205.165.92");//ip
        connectionFactory.setPort(5672);//端口号,默认是5672
        connectionFactory.setUsername("Test");//用户名
        connectionFactory.setPassword("123");//密码
        connectionFactory.setVirtualHost("TestVirtualHost");//设置操作的虚拟机
        Connection connection = connectionFactory.newConnection();//从连接工厂中获取到连接

        //2. 开启通道(Channel)
        Channel channel = connection.createChannel();//通过connection开启通道

        channel.basicQos(1);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String request = new String(body);

                String response = "响应成功!!!!!!!!!" + request;
                System.out.println(response);
                AMQP.BasicProperties basicProperties = new AMQP.BasicProperties()
                        .builder()
                        .correlationId(properties.getCorrelationId())
                        .build();

                channel.basicPublish("", "RPC_RESPONSE_QUEUE",basicProperties, response.getBytes());
                channel.basicAck(envelope.getDeliveryTag(),false);//手动确认
            }
        };

        //3.接受请求
        channel.basicConsume("RPC_REQUEST_QUEUE", false, consumer);


    }
}
